package gui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;

import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.ScrollPaneConstants;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.swing.JComboBox;

import messagesPacks.SimpleIntMessage;
import messagesPacks.SubscriberSearchBookMassege;
import messagesPacks.TOCMessage;
import messagesPacks.UsersMSG;

import javax.swing.border.BevelBorder;
import javax.swing.border.MatteBorder;
import javax.swing.JCheckBox;

import Entity.Book;
import Entity.User;
import javax.swing.border.CompoundBorder;
import javax.swing.border.LineBorder;
import javax.swing.border.TitledBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.UIManager;

import controllers.OBLSettings;
import controllers.SubscriberUIP;
import java.awt.SystemColor;
import javax.swing.ImageIcon;

import sun.awt.im.SimpleInputMethodWindow;
/**
 * This class representing a Subscriber Search a Book Gui
 * Date: 25/12/2012
 * @author Roman
 *
 */
public class SubscriberSearchBookUI extends JPanel 
{
	private static final long serialVersionUID = 1L;
	
	JTextField searchByBookNameFiled;
	JTextField searchByBookAuthorFiled;
	JTextField freeTextFiled;
	JLabel cantOrderLabel;
	JLabel lblByNameLabel;
	JLabel lblByAuthorLabel;
	JLabel lblBySubjectLabel;
	JLabel lblNewLabel_3;
	JSeparator separator;
	JLabel lblTitleLabel;
	JButton btnExit;
    JButton btnLogOut;
    private JButton btnBack;
    private JButton btnSearch;
    private SubscriberUI subUI = null ;
    public JComboBox <String> subjectcomboBox;
    
    Hashtable<Integer,String > BookSubjects = new Hashtable <Integer,String>();
    String selectedBookSubject ;
    String selectedBookSubjectID ;

    public SimpleTable searchResultTable ;
    
	private JButton btnClear;
	private JLabel lblOrder;
	private JButton btnOrder;
	private JButton btnViewToc;
	
    String ISBNtoOrder;
    int numOfCopiesAvailable;
    int totalNumOfCopiesForBook;
    int enableOrderButton ;
    
    SubscriberSearchBookMassege result_search_msg  ;
    private JLabel backgroundlabel;
    
    
    
	public SubscriberSearchBookUI(SubscriberUI fatherPanel)
	{
		super();
		initialize();
		System.out.println("SubscriberSearchBookUI created.");
		this.subUI = fatherPanel;
	}


	private void initialize() 
	{
	    this.setSize(OBLSettings.pane2Size[0],OBLSettings.pane2Size[1]);
		setLayout(null);
		searchByBookNameFiled = new JTextField();
		searchByBookNameFiled.setBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null));
		searchByBookNameFiled.setBounds(227, 70, 265, 24);
		searchByBookNameFiled.setFont(new Font("Tahoma", Font.PLAIN, 15));
		add(searchByBookNameFiled);
		searchByBookNameFiled.setColumns(10);
		
		searchByBookAuthorFiled = new JTextField();
		searchByBookAuthorFiled.setBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null));
		searchByBookAuthorFiled.setBounds(227, 123, 265, 24);
		searchByBookAuthorFiled.setFont(new Font("Tahoma", Font.PLAIN, 15));
		add(searchByBookAuthorFiled);
		searchByBookAuthorFiled.setColumns(10);
		
		freeTextFiled = new JTextField();
		freeTextFiled.setBackground(SystemColor.window);
		freeTextFiled.setBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null));
		freeTextFiled.setBounds(227, 213, 265, 24);
		freeTextFiled.setFont(new Font("Tahoma", Font.PLAIN, 15));
		add(freeTextFiled);
		freeTextFiled.setColumns(10);
		
		lblByNameLabel = new JLabel("Search Book by name :");
		lblByNameLabel.setBounds(51, 70, 166, 24);
		lblByNameLabel.setFont(new Font("Tahoma", Font.PLAIN, 14));
		add(lblByNameLabel);
		
		lblByAuthorLabel = new JLabel("Search Book by Author :");
		lblByAuthorLabel.setBounds(51, 123, 166, 24);
		lblByAuthorLabel.setFont(new Font("Tahoma", Font.PLAIN, 14));
		add(lblByAuthorLabel);
		
		lblBySubjectLabel = new JLabel("Search Book by subject :");
		lblBySubjectLabel.setBounds(51, 170, 166, 24);
		lblBySubjectLabel.setFont(new Font("Tahoma", Font.PLAIN, 14));
		add(lblBySubjectLabel);
		
		lblNewLabel_3 = new JLabel("Free text search :");
		lblNewLabel_3.setBounds(51, 212, 152, 24);
		lblNewLabel_3.setFont(new Font("Tahoma", Font.PLAIN, 14));
		add(lblNewLabel_3);
		
		separator = new JSeparator();
		separator.setBounds(-26, 57, 826, 24);
		add(separator);
		
		lblTitleLabel = new JLabel("OBL Search Books");
		lblTitleLabel.setBounds(276, -1, 247, 60);
		lblTitleLabel.setFont(new Font("Tahoma", Font.BOLD, 20));
		add(lblTitleLabel);
		
		btnLogOut = new JButton("Logout");
		btnLogOut.setBounds(614, 11, 83, 41);
		btnLogOut.setFont(new Font("Tahoma", Font.BOLD, 15));
		add(btnLogOut);
		
		btnExit = new JButton("Exit");
		btnExit.setBounds(707, 11, 83, 41);
		btnExit.setFont(new Font("Tahoma", Font.BOLD, 15));
		add(btnExit);
		
		btnSearch = new JButton("Search");
		btnSearch.setBounds(256, 258, 97, 41);

		btnSearch.setFont(new Font("Tahoma", Font.PLAIN, 15));
		add(btnSearch);
		
		btnBack = new JButton("Back");
		btnBack.setBounds(26, 11, 83, 41);
		btnBack.setFont(new Font("Tahoma", Font.BOLD, 15));
		add(btnBack);
	
		subjectcomboBox = new JComboBox<String>();
		subjectcomboBox.setBounds(227, 173, 265, 26);
		subjectcomboBox.setFont(new Font("Tahoma", Font.PLAIN, 13));
		add(subjectcomboBox);
		this.selectedBookSubject = ("");
		this.selectedBookSubjectID = (""); 
		 
		 
		Object ColNames[] = { "ISBN", "Book Name", "Author","Edition" ,"Publish Year","Description","Location","Copies","Wanted" };
		searchResultTable = new SimpleTable(null, ColNames, 10, 390, 780, 170);
		searchResultTable.setColCenter(searchResultTable.table.getColumnCount());
	    add(searchResultTable.tblScrollPane,BorderLayout.CENTER);
			
		btnClear = new JButton("Clear");
		btnClear.setFont(new Font("Tahoma", Font.PLAIN, 15));
		btnClear.setBounds(51, 258, 97, 41);
		add(btnClear);
		
		
		lblOrder = new JLabel("To order a book select a book from the search result.");
		lblOrder.setBorder(new TitledBorder(null, "", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		lblOrder.setFont(new Font("Tahoma", Font.PLAIN, 13));
		lblOrder.setBounds(10, 360, 391, 24);
		add(lblOrder);
		
		btnOrder = new JButton("Order");
		btnOrder.setFont(new Font("Tahoma", Font.PLAIN, 14));
		btnOrder.setBounds(466, 258, 97, 41);
		btnOrder.setEnabled(false);
		add(btnOrder);
		
		btnViewToc = new JButton("View TOC");
		btnViewToc.setFont(new Font("Tahoma", Font.PLAIN, 14));
		btnViewToc.setEnabled(false);
		btnViewToc.setBounds(657, 258, 97, 41);
		btnViewToc.setVisible(true);
		add(btnViewToc);
		
		cantOrderLabel = new JLabel("");
		cantOrderLabel.setFont(new Font("Tahoma", Font.PLAIN, 14));
		cantOrderLabel.setBounds(10, 538, 331, 26);
		add(cantOrderLabel);
		
		backgroundlabel = new JLabel("");
		//backgroundlabel.setIcon(OBLSettings.IMG_SUBSCRIBER_SEARCH_BOOK_BACKGROUND);
		backgroundlabel.setBounds(0, 59, 800, 541);
		add(backgroundlabel);		
		
//================================================================		
//              Action Listeners
//================================================================
		btnClear.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent arg0)
			{
				 searchByBookNameFiled.setText("");
				 searchByBookAuthorFiled.setText("");
				 freeTextFiled.setText("");
				 searchResultTable.model.setRowCount(0);	 
				 subjectcomboBox.setSelectedItem("Please select subject...");
				 selectedBookSubject = ("Please select subject...");
				 selectedBookSubjectID =("0");
				 btnOrder.setEnabled(false);
				 btnViewToc.setEnabled(false);
			}
		});
//================================================================			
		btnBack.addActionListener(new ActionListener() 
		{
			public void actionPerformed(ActionEvent e) 
			{
				 searchByBookNameFiled.setText("");
				 searchByBookAuthorFiled.setText("");
				 freeTextFiled.setText("");
				 searchResultTable.model.setRowCount(0);
				 subjectcomboBox.setSelectedItem("Please select subject...");
		         selectedBookSubject = ("Please select subject...");
		         selectedBookSubjectID =("0");
		         btnOrder.setEnabled(false);
		         btnViewToc.setEnabled(false);
                 WelcomeUI.wui.switchPanel("OBL System - Subscriber",subUI ,OBLSettings.pane2Size[0], OBLSettings.pane2Size[1]);
			}
		});
		
//================================================================		
		btnSearch.addActionListener(new ActionListener() 
		{
			public void actionPerformed(ActionEvent e)
			{	
				
				searchResultTable.model.setRowCount(0);
				
				result_search_msg = subUI.subscriberUIP.subscriberSearchBook( searchByBookNameFiled.getText() , searchByBookAuthorFiled.getText() , selectedBookSubject 
																			,selectedBookSubjectID, freeTextFiled.getText() );
				if(result_search_msg == null)
					JOptionPane.showMessageDialog( WelcomeUI.wui, "Please fill at least one of the searching filleds" ,"Warning",JOptionPane.WARNING_MESSAGE);
				
				else 
				  if(result_search_msg.getQueryResult() == 0)
					 JOptionPane.showMessageDialog( WelcomeUI.wui, "There was an error in search, please try again ","Warning",JOptionPane.WARNING_MESSAGE);
				else
				 {
					if(result_search_msg.result_books.isEmpty())
						JOptionPane.showMessageDialog( WelcomeUI.wui, " No matching books found ","",JOptionPane.INFORMATION_MESSAGE);	
					else
					{	
						//JOptionPane.showMessageDialog( WelcomeUI.wui, " search succeed ","Done",JOptionPane.INFORMATION_MESSAGE);
						String wanted ; 
						for(Book var : result_search_msg.result_books)
						{
							if(var.getWanted().equalsIgnoreCase("0"))
								wanted = "no" ;
							else
								wanted = "yes" ;
						 
							searchResultTable.model.addRow(new Object[] {var.getISBN(),var.getBookName(),var.getBookAuthor(),var.getEdition(),var.getPublishYear()
														,var.getDescription(),var.getShelfLocation(),var.getBookNumOfCopies(),wanted});
						 
							//searchResultTable.table.repaint();
						
						}
				
						
					}
				 }
	
			}
		});

//================================================================		

	subjectcomboBox.addActionListener(new ActionListener()
	{
		public void actionPerformed(ActionEvent e)
		{
			 JComboBox cb = (JComboBox)e.getSource();
			 Set set = BookSubjects.entrySet();
			 Iterator it = set.iterator();
			 
			    while (it.hasNext()) 
			    {
			        Map.Entry entry = (Map.Entry) it.next();
			        if(entry.getValue().equals(cb.getSelectedItem()))
			        { 
			    	  System.out.println(entry.getKey() + " : " + entry.getValue());
			    	  selectedBookSubject = entry.getValue().toString();
			    	  selectedBookSubjectID =  entry.getKey().toString();
			    	  
			        }
			    }
		 }
			  
	 });
//================================================================

	searchResultTable.table.getSelectionModel().addListSelectionListener(new ListSelectionListener() 
	{
		public void valueChanged(ListSelectionEvent e) 
		{
			JTable table = searchResultTable.table;

			if(table.getRowCount() > 0)	
			{	
				btnViewToc.setEnabled(true);
				int row = searchResultTable.table.getSelectedRow();
				if(enableOrderButton==1)
					btnOrder.setEnabled(true);
			   
				if(row>=0)
				{ 
					
		    		Object[] rowData = new Object[table.getColumnCount()];  
		    		for (int i = 0; i < table.getColumnCount(); i++) 
		    		{  
				         rowData[i] = table.getValueAt(row, i);  
		    		} 
		    		
		    		 numOfCopiesAvailable = Integer.parseInt(rowData[7].toString());
		    		 ISBNtoOrder = rowData[0].toString();
					 if(enableOrderButton==0)
						JOptionPane.showMessageDialog( WelcomeUI.wui, "you cannot order books because you are suspended !","Suspended",JOptionPane.WARNING_MESSAGE);
				}
			}
		}
		
	});
	
//================================================================			
	btnOrder.addActionListener(new ActionListener() 
	{
		public void actionPerformed(ActionEvent arg0) 
		{
			int goodToOrder = 0;
			String NameOfOrderedBook ="";
			
			if(numOfCopiesAvailable > 0)
				JOptionPane.showMessageDialog( WelcomeUI.wui,"you can't order this book because there are available copies of the book in the library,\n please borrow the book from the librarian ","",JOptionPane.INFORMATION_MESSAGE);
			
			else
			{
				
				for(Book var : result_search_msg.result_books)
				{
					if(var.getISBN().equals(ISBNtoOrder))										//check if the total number of orders for the ISBNtoOrder isn't
					{																			//greater than the total number of copies for this ISBN
						if(var.getBookTotalNumOfCopies() > var.getNumOfOrdersForBook())
						{
							 goodToOrder = 1;
							 NameOfOrderedBook = var.getBookName();
						}
					}	
				 }	

				if( goodToOrder == 0)
					JOptionPane.showMessageDialog( WelcomeUI.wui, "The number of orders for this book reached the maximum\n" +
							                             ",please try to order later  ","Warning",JOptionPane.WARNING_MESSAGE);
				else
				{	

					//Date date = new Date();
					
					int result = subUI.subscriberUIP.OrderAbook(subUI.subscriber.getID(), ISBNtoOrder);
					
					     if( result == 1)
					     {		
					    	 JOptionPane.showMessageDialog( WelcomeUI.wui," Order has been placed for book :" +
										" "+NameOfOrderedBook,"",JOptionPane.INFORMATION_MESSAGE);
					     }
					     else 
					     if(result == 2)
					    	 JOptionPane.showMessageDialog( WelcomeUI.wui,"you already placed an order on this book ","",JOptionPane.WARNING_MESSAGE);
					     else
					     if(result == 3)
					    	 JOptionPane.showMessageDialog( WelcomeUI.wui,"you already have this book in borrow","",JOptionPane.WARNING_MESSAGE);
					     else
						   JOptionPane.showMessageDialog( WelcomeUI.wui,"There was a problem in your order , please try again later ","",JOptionPane.WARNING_MESSAGE);
				}
			 }
		}
	});
	
	//===================================================================
	btnViewToc.addActionListener(new ActionListener() 
	{
		public void actionPerformed(ActionEvent arg0) 
		{
			// Request TOC file from the server
			
			if (ISBNtoOrder != null)
			{
				TOCMessage toc_result = subUI.subscriberUIP.requestTOC(ISBNtoOrder);
				if (toc_result.getSuccess())
				{
					//JOptionPane.showMessageDialog( WelcomeUI.wui,"TOC Saved to your local directory!","View TOC",JOptionPane.INFORMATION_MESSAGE);
				}
				else
				{
					JOptionPane.showMessageDialog( WelcomeUI.wui,"Sorry, TOC doesn't exist for this book.","View TOC",JOptionPane.WARNING_MESSAGE);
				}
			}
			else
				JOptionPane.showMessageDialog( WelcomeUI.wui,"Error! No Book selected!","View TOC",JOptionPane.WARNING_MESSAGE);
		}
	});
	//===================================================================
	freeTextFiled.addActionListener(new ActionListener()
	{
        public void actionPerformed(ActionEvent e)
        {
                btnSearch.doClick();
        }  
    });

	 searchByBookAuthorFiled.addActionListener(new ActionListener()
	{
        public void actionPerformed(ActionEvent e)
        {
                btnSearch.doClick();
        }  
    });
	
	 searchByBookNameFiled.addActionListener(new ActionListener()
	{
        public void actionPerformed(ActionEvent e)
        {
                btnSearch.doClick();
        }  
    });

  }//initialize
	


//===================================================================	
//                	Getters & Setters
//===================================================================	
	public String getSearchByBookNameFiled()
	{
		return searchByBookNameFiled.getText();
	}



	public void setSearchByBookNameFiled(JTextField searchByBookNameFiled)
	{
		this.searchByBookNameFiled = searchByBookNameFiled;
	}



	public String getSearchByBookAuthorFiled() 
	{
		return searchByBookAuthorFiled.getText();
	}



	public void setSearchByBookAuthorFiled(JTextField searchByBookAuthorFiled)
	{
		this.searchByBookAuthorFiled = searchByBookAuthorFiled;
	}



	public String getFreeTextFiled() 
	{
		return freeTextFiled.getText();
	}

	public void setFreeTextFiled(JTextField freeTextFiled) 
	{
		this.freeTextFiled = freeTextFiled;
	}
	

	public String getSelectedBookSubject()
	{
		return selectedBookSubject;
	}



	public void setSelectedBookSubject(String selectedBookSubject) 
	{
		this.selectedBookSubject = selectedBookSubject;
	}



	public String getSelectedBookSubjectID() 
	{
		return selectedBookSubjectID;
	}



	public void setSelectedBookSubjectID(String selectedBookSubjectID) 
	{
		this.selectedBookSubjectID = selectedBookSubjectID;
	}
	
	public void paintComponent(Graphics g) 
	{
		g.drawImage((OBLSettings.IMG_DEFAULT_BACKGROUND).getImage(), 0, 0, OBLSettings.pane2Size[0], OBLSettings.pane2Size[1],null);
		
	}
	
	
}//class
